<template>
  <div class="user-management-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <div class="header-title">
            <el-icon color="#409EFF"><User /></el-icon>
            <span>用户管理</span>
          </div>
          <div class="header-actions">
            <el-button type="primary" @click="refreshData">
              <el-icon><Refresh /></el-icon>
              刷新数据
            </el-button>
          </div>
        </div>
      </template>

      <!-- 用户筛选 -->
      <div class="filter-container">
        <el-form :inline="true" :model="filters" class="filter-form">
          <el-form-item label="用户类型">
            <el-select v-model="filters.userType" placeholder="全部类型" clearable>
              <el-option label="管理员" value="admin" />
              <el-option label="司机（已认证）" value="driver" />
              <el-option label="学生（已认证）" value="student" />
              <el-option label="普通用户" value="normal" />
            </el-select>
          </el-form-item>
          <el-form-item label="搜索">
            <el-input v-model="filters.search" placeholder="用户昵称/手机号" clearable />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchUsers">搜索</el-button>
            <el-button @click="resetFilters">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 用户统计 -->
      <div class="statistics-container">
        <el-row :gutter="16">
          <el-col :span="6">
            <el-statistic title="总用户数" :value="total" />
          </el-col>
          <el-col :span="6">
            <el-statistic title="管理员" :value="adminCount" />
          </el-col>
          <el-col :span="6">
            <el-statistic title="司机认证" :value="driverCount" />
          </el-col>
          <el-col :span="6">
            <el-statistic title="学生认证" :value="studentCount" />
          </el-col>
        </el-row>
      </div>

      <!-- 用户列表 -->
      <div class="users-list">
        <el-table
          :data="usersList"
          border
          style="width: 100%"
          v-loading="loading"
        >
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="nickname" label="用户昵称" width="120" />
          <el-table-column prop="phone" label="手机号" width="120" />
          <el-table-column label="管理员" width="80" align="center">
            <template #default="scope">
              <el-tag v-if="scope.row.isAdmin" type="danger" size="small">是</el-tag>
              <el-tag v-else type="info" size="small">否</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="司机认证" width="80" align="center">
            <template #default="scope">
              <el-tag v-if="scope.row.isDriver" type="success" size="small">已认证</el-tag>
              <el-tag v-else type="info" size="small">未认证</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="学生认证" width="80" align="center">
            <template #default="scope">
              <el-tag v-if="scope.row.isBoundStudentInfo" type="warning" size="small">已认证</el-tag>
              <el-tag v-else type="info" size="small">未认证</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="注册时间" width="180">
            <template #default="scope">
              {{ formatDate(scope.row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="120">
            <template #default="scope">
              <el-button size="small" type="primary" @click="handleEditUser(scope.row)">编辑</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>

    <!-- 用户编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
    >
      <el-form :model="userForm" label-width="120px" ref="userFormRef" :rules="userRules">
        <el-form-item label="用户昵称" prop="nickname">
          <el-input v-model="userForm.nickname" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone" />
        </el-form-item>
        <el-form-item label="头像URL" prop="avatarUrl">
          <el-input v-model="userForm.avatarUrl" placeholder="可选，用户头像地址" />
        </el-form-item>
        <el-form-item label="管理员权限">
          <el-switch 
            v-model="userForm.isAdmin" 
            active-text="是" 
            inactive-text="否"
            active-color="#F56C6C"
            inactive-color="#409EFF"
          />
          <div class="form-tip">管理员可以访问系统管理功能</div>
        </el-form-item>
        <el-form-item label="司机认证状态">
          <el-tag v-if="userForm.isDriver" type="success">已认证</el-tag>
          <el-tag v-else type="info">未认证</el-tag>
          <div class="form-tip">司机认证需要通过资质审核流程</div>
        </el-form-item>
        <el-form-item label="学生认证状态">
          <el-tag v-if="userForm.isBoundStudentInfo" type="warning">已认证</el-tag>
          <el-tag v-else type="info">未认证</el-tag>
          <div class="form-tip">学生认证需要用户自行绑定学生信息</div>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="isAddingUser">
          <el-input v-model="userForm.password" type="password" show-password />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitUserForm">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { User, Refresh, Plus } from '@element-plus/icons-vue'
import { getAllUsers, addUser, updateUser, deleteUser, changeUserStatus } from '@/api/user'

// 检查是否有adminRoot权限
const checkAdminRoot = () => {
  const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
  if (userInfo.phone !== 'adminRoot') {
    ElMessage.error('您没有权限访问此页面')
    // 重定向到首页或其他页面
    window.location.href = '/'
    return false
  }
  return true
}

// 加载状态
const loading = ref(false)

// 分页参数
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 筛选条件
const filters = reactive({
  userType: '',
  search: ''
})

// 原始用户数据
const originalUsersList = ref([])

// 用户列表数据
const usersList = ref([])

// 计算统计数据
const adminCount = computed(() => {
  return usersList.value.filter(user => user.isAdmin).length
})

const driverCount = computed(() => {
  return usersList.value.filter(user => user.isDriver).length
})

const studentCount = computed(() => {
  return usersList.value.filter(user => user.isBoundStudentInfo).length
})

// 重置筛选条件
const resetFilters = () => {
  filters.userType = ''
  filters.search = ''
  applyFilters()
}

// 搜索用户
const searchUsers = () => {
  currentPage.value = 1
  applyFilters()
}

// 应用前端筛选
const applyFilters = () => {
  let filteredList = [...originalUsersList.value]
  
  // 按用户类型筛选
  if (filters.userType) {
    filteredList = filteredList.filter(user => {
      if (filters.userType === 'admin') return user.isAdmin
      if (filters.userType === 'driver') return user.isDriver
      if (filters.userType === 'student') return user.isBoundStudentInfo
      if (filters.userType === 'normal') return !user.isAdmin && !user.isDriver && !user.isBoundStudentInfo
      return true
    })
  }
  
  // 按搜索关键词筛选
  if (filters.search) {
    const search = filters.search.toLowerCase()
    filteredList = filteredList.filter(user => 
      (user.nickname && user.nickname.toLowerCase().includes(search)) ||
      (user.phone && user.phone.toLowerCase().includes(search))
    )
  }
  
  usersList.value = filteredList
  total.value = filteredList.length
}

// 日期格式化函数
const formatDate = (dateTime) => {
  if (!dateTime) return ''
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 获取用户列表
const fetchUsersList = () => {
  loading.value = true
  
  // 调用API获取用户列表
  getAllUsers()
    .then(response => {
      if (response.code === 1) {
        originalUsersList.value = response.data || []
        
        // 应用前端筛选
        applyFilters()
      } else {
        ElMessage.error(response.msg || '获取用户列表失败')
      }
    })
    .catch(error => {
      console.error('获取用户列表失败', error)
      ElMessage.error('获取用户列表失败')
      
      // 如果API未实现，使用模拟数据
      mockUsersList()
    })
    .finally(() => {
      loading.value = false
    })
}

// 模拟用户列表数据 - 仅在API未实现时使用
const mockUsersList = () => {
  // 模拟数据
  originalUsersList.value = [
    {
      id: 1,
      nickname: 'admin',
      realName: '管理员',
      phone: 'admin',
      email: 'admin@example.com',
      isAdmin: true,
      isDriver: false,
      status: 'normal',
      createTime: '2023-01-01 00:00:00'
    },
    {
      id: 2,
      nickname: 'adminRoot',
      realName: '超级管理员',
      phone: 'adminRoot',
      email: 'adminroot@example.com',
      isAdmin: true,
      isDriver: false,
      status: 'normal',
      createTime: '2023-01-01 00:00:00'
    },
    {
      id: 3,
      nickname: 'driver1',
      realName: '司机1',
      phone: '13800138001',
      email: 'driver1@example.com',
      isAdmin: false,
      isDriver: true,
      status: 'normal',
      createTime: '2023-01-02 00:00:00'
    },
    {
      id: 4,
      nickname: 'passenger1',
      realName: '乘客1',
      phone: '13800138002',
      email: 'passenger1@example.com',
      isAdmin: false,
      isDriver: false,
      status: 'normal',
      createTime: '2023-01-03 00:00:00'
    }
  ]
  
  // 应用筛选条件
  if (filters.userType) {
    originalUsersList.value = originalUsersList.value.filter(user => {
      if (filters.userType === 'admin') return user.isAdmin
      if (filters.userType === 'driver') return user.isDriver
      if (filters.userType === 'student') return user.isBoundStudentInfo
      if (filters.userType === 'normal') return !user.isAdmin && !user.isDriver && !user.isBoundStudentInfo
      return true
    })
  }
  
  if (filters.search) {
    const search = filters.search.toLowerCase()
    originalUsersList.value = originalUsersList.value.filter(user => 
      user.nickname.toLowerCase().includes(search) || 
      user.phone.toLowerCase().includes(search) ||
      (user.realName && user.realName.toLowerCase().includes(search))
    )
  }
  
  total.value = originalUsersList.value.length
}

// 刷新数据
const refreshData = () => {
  fetchUsersList()
}

// 处理页面大小变化
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchUsersList()
}

// 处理当前页变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchUsersList()
}

// 用户表单相关
const dialogVisible = ref(false)
const dialogTitle = ref('添加用户')
const userFormRef = ref(null)
const isAddingUser = ref(false)
const userForm = reactive({
  id: null,
  nickname: '',
  phone: '',
  avatarUrl: '',
  isAdmin: false,
  isDriver: false,
  isBoundStudentInfo: false,
  password: ''
})

// 表单验证规则
const userRules = {
  nickname: [{ required: true, message: '请输入用户昵称', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur', validator: (rule, value, callback) => {
      if (isAddingUser.value && !value) {
        callback(new Error('请输入密码'))
      } else {
        callback()
      }
    }}
  ]
}

// 添加用户
const handleAddUser = () => {
  resetUserForm()
  isAddingUser.value = true
  dialogTitle.value = '添加用户'
  dialogVisible.value = true
}

// 编辑用户
const handleEditUser = (user) => {
  resetUserForm()
  isAddingUser.value = false
  dialogTitle.value = '编辑用户'
  
  userForm.id = user.id
  userForm.nickname = user.nickname
  userForm.phone = user.phone
  userForm.avatarUrl = user.avatarUrl || ''
  userForm.isAdmin = user.isAdmin || false
  userForm.isDriver = user.isDriver || false
  userForm.isBoundStudentInfo = user.isBoundStudentInfo || false
  
  dialogVisible.value = true
}

// 重置表单
const resetUserForm = () => {
  userForm.id = null
  userForm.nickname = ''
  userForm.phone = ''
  userForm.avatarUrl = ''
  userForm.isAdmin = false
  userForm.isDriver = false
  userForm.isBoundStudentInfo = false
  userForm.password = ''
  
  if (userFormRef.value) {
    userFormRef.value.resetFields()
  }
}

// 提交用户表单
const submitUserForm = async () => {
  if (!userFormRef.value) return
  
  try {
    await userFormRef.value.validate()
    
    // 准备提交的数据
    const submitData = {
      nickname: userForm.nickname,
      phone: userForm.phone,
      avatarUrl: userForm.avatarUrl,
      isAdmin: userForm.isAdmin
    }
    
    if (isAddingUser.value) {
      // 添加用户时，司机和学生认证默认为false
      submitData.password = userForm.password
      submitData.isDriver = false
      submitData.isBoundStudentInfo = false
      
      // 调用添加用户API
      addUser(submitData)
        .then(response => {
          if (response.code === 1) {
            ElMessage.success('添加用户成功')
            dialogVisible.value = false
            fetchUsersList()
          } else {
            ElMessage.error(response.msg || '添加用户失败')
          }
        })
        .catch(error => {
          console.error('添加用户失败', error)
          ElMessage.error('添加用户失败')
          dialogVisible.value = false
        })
    } else {
      // 编辑用户时，保持原有的司机和学生认证状态
      submitData.id = userForm.id
      submitData.isDriver = userForm.isDriver
      submitData.isBoundStudentInfo = userForm.isBoundStudentInfo
      
      // 调用更新用户API
      updateUser(submitData)
        .then(response => {
          if (response.code === 1) {
            ElMessage.success('更新用户成功')
            dialogVisible.value = false
            fetchUsersList()
          } else {
            ElMessage.error(response.msg || '更新用户失败')
          }
        })
        .catch(error => {
          console.error('更新用户失败', error)
          ElMessage.error('更新用户失败')
          dialogVisible.value = false
        })
    }
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

// 删除用户功能暂时移除，因为后端没有对应接口
const handleDeleteUser = (user) => {
  ElMessage.warning('删除功能暂未开放，请联系系统管理员')
}

// 状态切换功能暂时移除，因为后端没有对应接口
const handleToggleStatus = (user) => {
  ElMessage.warning('状态切换功能暂未开放，请联系系统管理员')
}

// 组件挂载后执行
onMounted(() => {
  // 检查权限
  if (checkAdminRoot()) {
    fetchUsersList()
  }
})
</script>

<style scoped>
.user-management-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title {
  display: flex;
  align-items: center;
  font-size: 18px;
  font-weight: bold;
}

.header-title .el-icon {
  margin-right: 8px;
  font-size: 20px;
}

.filter-container {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
}

.users-list {
  margin-top: 20px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
  line-height: 1.4;
}

.statistics-container {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 4px;
}
</style> 